package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Goods;
import net.mujiwulian.entity.GoodsType;
import net.mujiwulian.service.GoodsDetailsService;
import net.mujiwulian.service.GoodsService;
import net.mujiwulian.service.GoodsTypeService;
import net.mujiwulian.view.GoodsDetails;
import net.mujiwulian.view.UserSimple;
import net.mujiwulian.vo.PageQuery;
import net.mujiwulian.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/28 14:24
 */
@Slf4j
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Value("${file-path}")
    private String filePath;

    private final GoodsService goodsService;
    private final GoodsTypeService goodsTypeService;
    private final GoodsDetailsService goodsDetailsService;

    public GoodsController(GoodsService goodsService, GoodsTypeService goodsTypeService, GoodsDetailsService goodsDetailsService) {
        this.goodsService = goodsService;
        this.goodsTypeService = goodsTypeService;
        this.goodsDetailsService = goodsDetailsService;
    }

    /**
     * ----------------------------------------------商品---------------------------------------------------
     */

    @PostMapping("/select")
    public Result<IPage<GoodsDetails>> select(@RequestBody PageQuery<GoodsDetails> pageQuery) {
        GoodsDetails goodsDetails = pageQuery.getT() == null ? new GoodsDetails() : pageQuery.getT();
        LambdaQueryWrapper<GoodsDetails> lq = Wrappers.lambdaQuery();
        lq.like(StringUtils.isNotEmpty(goodsDetails.getTypeName()), GoodsDetails::getTypeName, goodsDetails.getTypeName());
        lq.like(StringUtils.isNotEmpty(goodsDetails.getName()), GoodsDetails::getName, goodsDetails.getName());
        return new Result<>(Result.CodeStatus.OK, "获取商品信息", goodsDetailsService.page(pageQuery.getPageCondition(), lq));
    }

    @PostMapping("/insertOrUpdate")
    public Result<Void> insertOrUpdate(Goods goods) {
        Goods gs = null;
        if (goods.getId() != null) {
            gs = goodsService.getById(goods.getId());
        } else {
            if (!goodsService.list(new QueryWrapper<Goods>().eq("name", goods.getName())).isEmpty()) {
                return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
            }
        }
        try {
            if (goods.getImg() != null) {
                String path = "/files/goods/" + UUID.randomUUID().toString() + goods.getImg().getOriginalFilename();
                FileUtils.copyInputStreamToFile(goods.getImg().getInputStream(), new File(this.filePath + path));
                goods.setImgUrl(path);
                if (gs != null) {
                    File deleteFile = new File(this.filePath + gs.getImgUrl());
                    log.warn("删除文件:" + gs.getImgUrl() + "-----" + deleteFile.delete());
                }
            }
            if (goods.getImgDetails() != null) {
                String path = "/files/goods" + UUID.randomUUID().toString() + goods.getImgDetails().getOriginalFilename();
                FileUtils.copyInputStreamToFile(goods.getImgDetails().getInputStream(), new File(this.filePath + path));
                goods.setImgDetailsUrl(path);
                if (gs != null) {
                    File deleteFile = new File(this.filePath + gs.getImgDetailsUrl());
                    log.warn("删除文件:" + gs.getImgDetailsUrl() + "-----" + deleteFile.delete());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.CodeStatus.FAIL, "网络异常");
        }
        goods.setUpdateTime(LocalDateTime.now());
        return new Result<>("添加商品", goodsService.saveOrUpdate(goods));
    }

    @PostMapping("/delete")
    public Result<Void> delete(@RequestBody List<Integer> ids) {
        List<Goods> list = goodsService.list(new QueryWrapper<Goods>().in("id", ids).select("img_url", "img_details_url"));
        list.forEach(goods -> {
                    log.warn("删除文件:" + goods.getImgUrl() + "-----" + new File(this.filePath + goods.getImgUrl()).delete());
                    log.warn("删除文件:" + goods.getImgDetailsUrl() + "-----" + new File(this.filePath + goods.getImgDetailsUrl()).delete());
                }
        );
        return new Result<>("删除商品", goodsService.removeByIds(ids));
    }

    /**
     * ----------------------------------------------商品分类---------------------------------------------------
     */

    @GetMapping("/type/select")
    public Result<List<GoodsType>> selectType(boolean b) {
        LambdaQueryWrapper<GoodsType> lq = Wrappers.lambdaQuery();
        if (b) {
            lq.select(GoodsType::getId, GoodsType::getName);
        }
        return new Result<>(Result.CodeStatus.OK, "获取商品分类信息", goodsTypeService.list(lq));
    }

    @PostMapping("/type/delete")
    @Transactional(rollbackFor = {Exception.class})
    public Result<Void> deleteType(@RequestBody GoodsType goodsType) {
        //删除分类图片
        goodsType = goodsTypeService.getById(goodsType.getId());
        if (goodsType == null) {
            return new Result<>(Result.CodeStatus.FAIL, "资源不存在");
        }
        File deleteFile = new File(this.filePath + goodsType.getImgUrl());
        log.warn("删除文件:" + goodsType.getImgUrl() + "-----" + deleteFile.delete());
        return new Result<>("删除商品分类", goodsTypeService.removeById(goodsType.getId()));
    }

    @PostMapping("/type/insertOrUpdate")
    public Result<Void> insertOrUpdateType(UserSimple userSimple, GoodsType goodsType) {
        GoodsType gt = null;
        if (goodsType.getId() != null) {
            gt = goodsTypeService.getById(goodsType.getId());
        } else {
            if (!goodsTypeService.list(new QueryWrapper<GoodsType>().eq("name", goodsType.getName())).isEmpty()) {
                return new Result<>(Result.CodeStatus.FAIL, "名字已存在");
            }
            goodsType.setCreateTime(LocalDateTime.now());
        }
        if (goodsType.getImg() != null) {
            String path = "/files/goods/type/" + UUID.randomUUID().toString() + goodsType.getImg().getOriginalFilename();
            goodsType.setImgUrl(path);
            try {
                FileUtils.copyInputStreamToFile(goodsType.getImg().getInputStream(), new File(this.filePath + path));
            } catch (IOException e) {
                e.printStackTrace();
                return new Result<>(Result.CodeStatus.FAIL, "网络异常");
            }
            if (gt != null) {
                File deleteFile = new File(this.filePath + gt.getImgUrl());
                log.warn("删除文件:" + gt.getImgUrl() + "-----" + deleteFile.delete());
            }
        }
        goodsType.setUpdateTime(LocalDateTime.now());
        goodsType.setOperator(userSimple.getUsername());
        return new Result<>("操作", goodsTypeService.saveOrUpdate(goodsType));
    }
}
